﻿using Microsoft.Extensions.Logging;

namespace Devonline.AspNetCore;

/// <summary>
/// 简易的事件流程模型
/// </summary>
/// <typeparam name="TEventArgs"></typeparam>
public class EventPipeline<TEventArgs>
{
    private readonly ILogger<EventPipeline<TEventArgs>> _logger;
    /// <summary>
    /// 数据订阅事件
    /// </summary>
    private readonly IDictionary<string, EventHandler<TEventArgs>> _eventHandlers;

    /// <summary>
    /// 构造方法
    /// </summary>
    public EventPipeline(ILogger<EventPipeline<TEventArgs>> logger)
    {
        _logger = logger;
        _eventHandlers = new Dictionary<string, EventHandler<TEventArgs>>();
    }

    /// <summary>
    /// 订阅事件
    /// </summary>
    /// <param name="eventName"></param>
    /// <param name="eventHandler"></param>
    public void Subscribe(string eventName, EventHandler<TEventArgs> eventHandler)
    {
        _logger.LogInformation("注册事件 {eventName}", eventName);
        if (_eventHandlers.ContainsKey(eventName))
        {
            _eventHandlers[eventName] += eventHandler;
        }
        else
        {
            _eventHandlers.Add(eventName, eventHandler);
        }
    }

    /// <summary>
    /// 执行 eventName 开始的管道事件
    /// </summary>
    /// <param name="eventName">执行事件名称</param>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void Execute(string eventName, object? sender, TEventArgs e)
    {
        if (!string.IsNullOrWhiteSpace(eventName) && _eventHandlers.ContainsKey(eventName))
        {
            _logger.LogInformation("即将执行事件 {eventName} 的处理方法", eventName);
            _eventHandlers[eventName](sender, e);
        }
    }
}
